#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "command.h"
#include "uart_manager.h"
#include "command_manager.h"

int32_t at_command_execute(Command *self, char *response, size_t response_size)
{
    UARTManager *uart_manager = get_uart_manager();
    if (uart_manager == NULL)
    {
        printf("UART manager not initialized\n");
        return -1;
    }
    return send_at_command(uart_manager, self->command, response, response_size);
}

// 创建命令函数
Command *create_command(const char *format, ...)
{
    va_list args;
    va_start(args, format);

    // 动态分配内存以存储命令字符串
    char *command = NULL;
    int length = vsnprintf(command, 0, format, args); // 获取命令字符串的长度
    if (length < 0)
    {
        va_end(args);
        return NULL;
    }

    command = (char *)malloc(length + 1); // 分配足够的内存
    if (command == NULL)
    {
        va_end(args);
        return NULL;
    }

    // 根据格式和参数填充命令字符串
    vsnprintf(command, length + 1, format, args);
    va_end(args);

    // 创建 Command 实例
    Command *cmd = (Command *)malloc(sizeof(Command));
    if (cmd == NULL)
    {
        free(command);
        return NULL;
    }

    cmd->command = command;
    cmd->execute = execute_command; // 假设有一个 execute_command 函数实现命令执行逻辑

    return cmd;
}
void free_command(Command *cmd)
{
    if (cmd != NULL)
    {
        free(cmd->command);
        free(cmd);
    }
}